package com.llq.report;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;

import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;

import com.llq.studentinfo.Course;
import com.llq.studentinfo.CourseSession;
import com.llq.studentinfo.Session;
import com.llq.studentinfo.Student;
import com.llq.util.DateUtil;

public class RosterRporterTest {

	Session session;
	// public static final String NEWLINE =
	// System.getProperty("line.separator");
	static final String department = "ENGL";
	static final String number = "103";
	static final String name1 = "lee";
	static final String name2 = "lee2";
	Date startDate;
	Date endDate;

	@Before
	public void before() {
		startDate = DateUtil.creatDate(2009, 5, 1);
		endDate = DateUtil.creatDate(2009, 8, 18);
		session = CourseSession.creat(new Course(department, number),
				startDate);
		session.enroll(new Student("A"));
		session.enroll(new Student("B"));
	}

	@Test
	public void rosterReportTest() throws IOException {


		// String reportTest=RosterRoprter.ROSTER_REPORT_HEADER
		// +"A"+LineUtil.NEWLINE
		// +"B"+LineUtil.NEWLINE
		// +RosterRoprter.ROSTER_REPORT_FOOTER+"2"+LineUtil.NEWLINE;
		// String report=new RosterRoprter(courseSession).getReport();
		// Assert.assertEquals(reportTest, report);

		Writer writer = new StringWriter();
		new RosterRoprter(session).writeReport(writer);
		assertReportContents(writer.toString());
		
	}

	private void assertReportContents(String rosterReport) {
		String reportTest = String.format(RosterRoprter.ROSTER_REPORT_HEADER
				+ "A%n" + "B%n" + RosterRoprter.ROSTER_REPORT_FOOTER, 2);
		assertEquals(reportTest, rosterReport);
	}
	
	@Test
	public void fileReportTest() throws IOException{
		final String filename="fileReportTest.txt";
		
		try {
			delete(filename);
			
			new RosterRoprter(session).writeReport(filename);
			
			StringBuilder builder=new StringBuilder();
			String line;
			
			BufferedReader reader=new BufferedReader(new FileReader(filename));
			while ((line=reader.readLine())!=null) {
				builder.append(String.format(line+"%n"));
			}
			reader.close();
			
			assertReportContents(builder.toString());
		}finally{
			delete(filename);
		}
	}

	private void delete(String filename) {
		File file = new File(filename);
		if (file.exists()) {
			assertTrue("ubable to delete "+filename, file.delete());
		}
	}
	
}
